package com.sdkj.fixed.asset.assets.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.AppModelSelParam;
import com.sdkj.fixed.asset.api.assets.in_vo.Params;
import com.sdkj.fixed.asset.api.assets.in_vo.SetEmployeeSelf;
import com.sdkj.fixed.asset.api.assets.out_vo.SetClassEntity;
import com.sdkj.fixed.asset.api.assets.out_vo.StandModelEntity;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.CacheUtils;
import com.sdkj.fixed.asset.assets.util.JwtTokenUtil;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author niuliwei
 * @description 资产管理设置
 * @date 2020/7/21 9:12
 */
@Service
public class SetService extends BaseService<SetClass> {
    @Autowired
    private SetClassMapper classMapper;
    @Autowired
    private StandModelMapper standModelMapper;
    @Autowired
    private SetAreaMapper areaMapper;
    @Autowired
    private SetSupplierMapper supplierMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private AssetSupplierMapper assetSupplierMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Override
    public BaseMapper getMapper() {
        return classMapper;
    }

    /**
     * 资产分类-查询启用状态数据
     * @return
     */
    public List<SetClass> getAllEnClass(){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer i = reportMapper.selectUserIsAllDataAuth(userId);
        if(i==1){
            Example example = new Example(SetClass.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orgId", orgId);
            criteria.andEqualTo("isDeleted", 0);
            criteria.andEqualTo("state", 0);
            return classMapper.selectByExample(example);
        } else{
            List<SetClass> list = classMapper.getClassAuth(userId, orgId);
            List<String> strs = list.stream().map(SetClass::getId).collect(Collectors.toList());
            list.stream().forEach(e->{
                if(!strs.contains(e.getPid())){
                    e.setPid("");
                }
            });
            return list;
        }
    }

    /**
     * 资产分类-列表
     * @return
     */
    public List<SetClassEntity> getAllClass(){
        String orgId = request.getHeader("orgId");
        return classMapper.getAllByPid(orgId, null);
    }

    /**
     * 资产分类-分页查询
     * @return
     */
    public List<SetClassEntity> getAllClassPage(PageParams<Params> params){
        String orgId = request.getHeader("orgId");
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        return classMapper.getAllByPid(orgId, params.getParams().getId());
    }

    /**
     * 新增顶级和同级分类
     * @param setClass
     * @return
     */
    public SetClass addClass(SetClass setClass){
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");
        String orgId = request.getHeader("orgId");

        //编号唯一判断
        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("num", setClass.getNum());
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        SetClass setClass1 = classMapper.selectOneByExample(example);
        if(setClass1 != null){
            throw new LogicException("编号已存在");
        }

        setClass.setOrgId(orgId);
        setClass.setState(0);
        setClass.setIsDeleted(0);
        setClass.setCreateUser(userId);
        setClass.setCreateTime(TimeTool.getCurrentTimeStr());
        setClass.setUpdateUser(userId);
        setClass.setUpdateTime(TimeTool.getCurrentTimeStr());
        classMapper.insertSelective(setClass);

        SetClass setClass2 = new SetClass();
        setClass2.setId(setClass.getId());
        if(StringUtils.isNotBlank(setClass.getTreecode())){
            setClass2.setTreecode(setClass.getTreecode()+","+setClass.getId());
        }else{
            setClass2.setTreecode(setClass.getId());
        }
        classMapper.updateByPrimaryKeySelective(setClass2);
        return setClass;
    }

    /**
     * 新增下级分类
     * @param setClass
     * @return
     */
    public SetClass addLowerClass(SetClass setClass){
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");
        String orgId = request.getHeader("orgId");

        //编号唯一判断
        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("num", setClass.getNum());
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        SetClass  setClass1 = classMapper.selectOneByExample(example);
        if(setClass1 != null){
            throw new LogicException("编号已存在");
        }

        setClass.setOrgId(orgId);
        setClass.setState(0);
        setClass.setIsDeleted(0);
        setClass.setCreateUser(userId);
        setClass.setCreateTime(TimeTool.getCurrentTimeStr());
        setClass.setUpdateUser(userId);
        setClass.setUpdateTime(TimeTool.getCurrentTimeStr());
        classMapper.insertSelective(setClass);

        SetClass setClass2 = new SetClass();
        setClass2.setId(setClass.getId());
        if(StringUtils.isNotBlank(setClass.getTreecode())){
            setClass2.setTreecode(setClass.getTreecode()+","+setClass.getId());
        }else{
            setClass2.setTreecode(setClass.getId());
        }
        classMapper.updateByPrimaryKeySelective(setClass2);

        //新增下级时，如果当前直接父类有标准类型，则把标准类型转给新增的分类
        List<StandModelEntity> modelList = standModelMapper.getStandBySetId(setClass.getPid(), null, null, null);
        if(modelList != null && modelList.size() > 0){
            for (StandModelEntity entity : modelList) {
                StandModel model = new StandModel();
                model.setId(entity.getId());
                model.setSetId(setClass.getId());
                model.setUpdateUser(userId);
                model.setUpdateTime(TimeTool.getCurrentTimeStr());
                standModelMapper.updateByPrimaryKeySelective(model);

            }
        }

        // 新增下级时，如果当前直接父类有资产，则把资产转给新增的分类
        warehouseService.updateAssetClassId(setClass.getPid(),setClass.getId());

        //更新父级ifShow是否展示(0展示1不展示),
        SetClass s = new SetClass();
        s.setId(setClass.getPid());
        s.setIfShow(0);
        classMapper.updateByPrimaryKeySelective(s);
        return setClass;
    }


    /**
     * 根据id编辑资产分类
     * @param setClass
     * @return
     */
    public SetClass updClass(SetClass setClass){
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");
        String orgId = request.getHeader("orgId");

        //编号唯一判断
        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("num", setClass.getNum());
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        SetClass setClass1 = classMapper.selectOneByExample(example);
        if(setClass1 != null && !setClass1.getId().equals(setClass.getId())){
            throw new LogicException("编号已存在");
        }
       // String treeCode = "";
        //setClass.setTreecode(setClass.getId()+","+setClass.getTreecode());
        setClass.setUpdateUser(userId);
        setClass.setUpdateTime(TimeTool.getCurrentTimeStr());
        classMapper.updateByPrimaryKeySelective(setClass);
        return setClass;
    }

    /**
     *
     * 删除资产分类
     * @param id
     * @return
     */
    public void delClassById(String id){
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        //数据授权已使用不允许删除
        long c = classMapper.selDateAuthCount(id, 2);
        if(c > 0){
            throw new LogicException("数据授权已使用不允许删除");
        }

        //当前资产类别有子类别不允许删除
        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDeleted", 0);
        criteria.andEqualTo("pid", id);
        List<SetClass> list = classMapper.selectByExample(example);
        long count = list.stream().count();
        if(count > 0){
            throw new LogicException("当前资产类别有子类别不允许删除");
        }

        //当前资产类别有相关的资产数据不允许删除
        Example example1 = new Example(Warehouse.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("assetClassId", id);
        criteria1.andEqualTo("isDelete", 0);
        int cou = warehouseMapper.selectCountByExample(example1);
        if(cou > 0){
            throw new LogicException("当前资产类别有相关的资产数据不允许删除");
        }

        SetClass setClass = new SetClass();
        setClass.setId(id);
        setClass.setIsDeleted(1);
        setClass.setUpdateTime(TimeTool.getCurrentTimeStr());
        setClass.setUpdateUser(userId);
        classMapper.updateByPrimaryKeySelective(setClass);
    }

    /**
     *
     * 根据主键id启用、禁用资产分类
     * 禁用分类及所有子类
     * 启用当前分类
     * @param setClass
     * @return
     */
    public void classEnOrdisable(SetClass setClass){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        setClass.setUpdateTime(TimeTool.getCurrentTimeStr());
        setClass.setUpdateUser(userId);
        if(setClass.getState() == 0){
            classMapper.updateByPrimaryKeySelective(setClass);
        } else if (setClass.getState() == 1){

            //获取分类和其子类的id
            List<SetClass> list = new ArrayList<>();
            list.add(setClass);
            List<String> strList = new ArrayList<>();
            strList = getChildrenIdByPidP(list, strList);

            Example example = new Example(SetClass.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id", strList);
            classMapper.updateByExampleSelective(setClass, example);
        }

    }

    /**
     * 递归查询子分类获取分类id
     * @param list
     * @return
     */
    public List<String> getChildrenIdByPid(List<SetClass> list, List<String> strs){
        if(list!=null && list.size()>0){
            for (SetClass setClass : list) {
                strs.add(setClass.getId());
                List<SetClass> classList = getChildrenByPid(setClass.getId());
                if(classList!=null && classList.size()>0){
                    getChildrenIdByPid(classList, strs);
                }
            }
        }
        return strs;
    }
    /**
     * 递归查询子分类获取分类id，启用、禁用
     * @param list
     * @return
     */
    public List<String> getChildrenIdByPidP(List<SetClass> list, List<String> strs){
        if(list!=null && list.size()>0){
            for (SetClass setClass : list) {
                strs.add(setClass.getId());
                List<SetClass> classList = getChildrenByPidP(setClass.getId());
                if(classList!=null && classList.size()>0){
                    getChildrenIdByPidP(classList, strs);
                }
            }
        }
        return strs;
    }
    /**
     * 根据pid获取子节点,启用、禁用
     * @param pid
     * @return
     */
    public List<SetClass> getChildrenByPidP(String pid){
        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDeleted", 0);
        criteria.andEqualTo("pid", pid);
        criteria.andEqualTo("state", 0);
        List<SetClass> ChildrenNodeList = classMapper.selectByExample(example);
        return ChildrenNodeList;
    }


    /**
     *
     * 根据主键id查询资产分类
     * @param id
     * @return
     */
    public SetClassEntity selClassById(String id){
        return classMapper.selById(id);
    }

    /**
     * 资产分类获取所有父节点
     * @return
     */
    public List<SetClass> getParentNode(){
        String orgId = request.getHeader("orgId");

        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
//        criteria.andEqualTo("pid", "");
        criteria.andEqualTo("state", 0);
        criteria.andEqualTo("receiveBorrow", 0);
        List<SetClass> parentNodeList = classMapper.selectByExample(example);
        List<String> strs = parentNodeList.stream().map(SetClass::getId).collect(Collectors.toList());
        parentNodeList.stream().forEach(e->{
            if(!strs.contains(e.getPid())){
                e.setPid("");
            }
        });
        List<SetClass> list = new ArrayList<>();
        parentNodeList.stream().forEach(f->{
            if("".equals(f.getPid())){
                list.add(f);
            }
        });
        return list;
    }

    /**
     * 根据pid获取子节点
     * @param pid
     * @return
     */
    public List<SetClass> getChildrenByPid(String pid){
        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDeleted", 0);
        criteria.andEqualTo("pid", pid);
        criteria.andEqualTo("state", 0);
        criteria.andEqualTo("receiveBorrow", 0);
        List<SetClass> ChildrenNodeList = classMapper.selectByExample(example);
        return ChildrenNodeList;
    }

    /**
     * 递归查询子分类
     * @param list
     * @return
     */
    public List<SetClass> getChildrenNodeByPid(List<SetClass> list){
        if(list!=null && list.size()>0){
            for (SetClass setClass : list) {
                List<SetClass> classList = getChildrenByPid(setClass.getId());
                if(classList!=null && classList.size()>0){
                    setClass.setList(classList);
                    getChildrenNodeByPid(classList);
                }
            }
        }
        return list;
    }

    /**
     * 获取分类树
     * @return
     */
    public List<SetClass> getClassTree(){
        List<SetClass> classList = new ArrayList<>();
        List<SetClass> pClasss = getParentNode();
       if(pClasss!= null && pClasss.size()>0){
           classList = getChildrenNodeByPid(pClasss);
       }
        return classList;
    }

    /**
     * app
     * 查询指定分类以及其子类下的标准类型
     * @param params
     * @return
     */
    public List<StandModelEntity> getAllStandBySetId(AppModelSelParam params){
        String orgId = request.getHeader("orgId");
        //获取分类和其子类的id,如果classId为空，查询全部
        List<String> strList = new ArrayList<>();
        if(StringUtils.isBlank(params.getId())){
            Example example = new Example(SetClass.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("isDeleted", 0);
            criteria.andEqualTo("orgId", orgId);
            criteria.andEqualTo("state", 0);
            criteria.andEqualTo("receiveBorrow", 0);
//            criteria.andNotEqualTo("ifShow", 0);
            List<SetClass> scList = classMapper.selectByExample(example);
            strList = scList.stream().map(SetClass :: getId).collect(Collectors.toList());
        } else {
            SetClass setClass = new SetClass();
            setClass.setId(params.getId());
            List<SetClass> classList = new ArrayList<>();
            classList.add(setClass);

            strList = getChildrenIdByPid(classList, strList);
        }
        List<StandModelEntity> standList = standModelMapper.getStandBySetId(null, strList, params.getSearch(), params.getState());
        return standList;
    }



    /**
     * 根据分类id查询标准类型
     * @return
     */
    public List<StandModelEntity> getStandPageBySetId(PageParams<Params> params){
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        return standModelMapper.getStandBySetId(params.getParams().getId(), null, null, params.getParams().getState());
    }

    /**
     *
     * 新增资产型号
     * @param standModel
     * @return
     */
    public StandModel addStandModel(StandModel standModel){
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        //标准型号唯一判断
        Example example = new Example(StandModel.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("model", standModel.getModel());
        criteria.andEqualTo("setId", standModel.getSetId());
        criteria.andEqualTo("isDeleted", 0);
        StandModel standModel1 = standModelMapper.selectOneByExample(example);
        if(standModel1 != null){
            throw new LogicException("型号已存在");
        }

        standModel.setIsDeleted(0);
        standModel.setState(0);
        standModel.setCreateUser(userId);
        standModel.setCreateTime(TimeTool.getCurrentTimeStr());
        standModel.setUpdateUser(userId);
        standModel.setUpdateTime(TimeTool.getCurrentTimeStr());
        standModelMapper.insertSelective(standModel);
        return standModel;
    }

    /**
     *
     * 删除资产型号
     * @param id
     * @return
     */
    public void delStandModelById(String id){
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        //标准规格型号下有关联资产，不允许删除
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("standardModel", id);
        criteria.andEqualTo("isDelete", 0);
        int cou = warehouseMapper.selectCountByExample(example);
        if(cou > 0){
            throw new LogicException("标准规格型号下有关联资产，不允许删除");
        }

        StandModel standModel = new StandModel();
        standModel.setId(id);
        standModel.setIsDeleted(1);
        standModel.setUpdateTime(TimeTool.getCurrentTimeStr());
        standModel.setUpdateUser(userId);
        standModelMapper.updateByPrimaryKeySelective(standModel);
    }

    /**
     *
     * 根据主键查询资产标准型号
     * @param id
     * @return
     */
        public StandModelEntity selStandModelById(String id){
        return standModelMapper.selById(id);
    }

    /**
     *
     * 根据主键id启用、禁用资产型号
     * @param standModel
     * @return
     */
    public void standModelEnOrdisable(StandModel standModel){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        StandModel stand = new StandModel();
        stand.setId(standModel.getId());
        stand.setState(standModel.getState());
        stand.setUpdateTime(TimeTool.getCurrentTimeStr());
        stand.setUpdateUser(userId);
        standModelMapper.updateByPrimaryKeySelective(standModel);
    }

    /**
     *
     * 根据主键id编辑资产型号
     * @param standModel
     * @return
     */
    public StandModel updStandModel(StandModel standModel){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        //标准型号唯一判断
        Example example = new Example(StandModel.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("model", standModel.getModel());
        criteria.andEqualTo("setId", standModel.getSetId());
        criteria.andEqualTo("isDeleted", 0);
        StandModel standModel1 = standModelMapper.selectOneByExample(example);
        if(standModel1 != null && !standModel1.getId().equals(standModel.getId())){
            throw new LogicException("型号已存在");
        }

        standModel.setUpdateUser(userId);
        standModel.setUpdateTime(TimeTool.getCurrentTimeStr());
        standModelMapper.updateByPrimaryKeySelective(standModel);
        return standModel;
    }

    /**
     * 区域-新增
     * @param area
     * @return
     */
    public SetArea addArea(SetArea area){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        Example example = new Example(SetArea.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type", area.getType());
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        SetArea setArea = areaMapper.selectOneByExample(example);
        if(setArea != null){
            throw new LogicException("区域编号已存在");
        }

        area.setState(0);
        area.setIsDeleted(0);
        area.setCreateUser(userId);
        area.setCreateTime(TimeTool.getCurrentTimeStr());
        area.setUpdateUser(userId);
        area.setUpdateTime(TimeTool.getCurrentTimeStr());
        area.setOrgId(orgId);
        areaMapper.insertSelective(area);
        return area;
    }

    /**
     * 区域-编辑
     * @param area
     * @return
     */
    public SetArea updArea(SetArea area){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        Example example = new Example(SetArea.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type", area.getType());
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        SetArea setArea = areaMapper.selectOneByExample(example);
        if(setArea != null && !setArea.getId().equals(area.getId())){
            throw new LogicException("区域编号已存在");
        }

        area.setUpdateUser(userId);
        area.setUpdateTime(TimeTool.getCurrentTimeStr());
        areaMapper.updateByPrimaryKeySelective(area);
        return area;
    }

    /**
     * 区域-删除
     * @param id
     */
    public void delArea(String id){
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        //数据授权已使用不允许删除
        long c = classMapper.selDateAuthCount(id, 3);
        if(c > 0){
            throw new LogicException("数据授权已使用不允许删除");
        }

        //该区域下存在资产信息,不能进行删除！
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("area", id);
        criteria.andEqualTo("isDelete", 0);
        int cou = warehouseMapper.selectCountByExample(example);
        if(cou > 0){
            throw new LogicException("该区域下存在资产信息,不能进行删除");
        }

        SetArea area = new SetArea();
        area.setId(id);
        area.setIsDeleted(1);
        area.setUpdateUser(userId);
        area.setUpdateTime(TimeTool.getCurrentTimeStr());
        areaMapper.updateByPrimaryKeySelective(area);
    }

    /**
     * 区域-启用、禁用
     * @param area
     */
    public void enOrDisArea(SetArea area){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        area.setUpdateUser(userId);
        area.setUpdateTime(TimeTool.getCurrentTimeStr());
        areaMapper.updateByPrimaryKeySelective(area);
    }

    /**
     * 区域-分页查询
     * @param pageParams
     * @return
     */
    public List<SetArea> getAllPageArea(PageParams<SetArea> pageParams){
        String orgId = request.getHeader("orgId");

        PageHelper.startPage(pageParams.getCurrentPage(), pageParams.getPerPageTotal());
        Example example = new Example(SetArea.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        example.setOrderByClause("create_time DESC");
        return areaMapper.selectByExample(example);
    }

    /**
     * 区域-启用列表,如果是普通管理员查询已授权的
     * @return
     */
    public List<SetArea> getAllArea(){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer i = reportMapper.selectUserIsAllDataAuth(userId);
        if(i==1){
            Example example = new Example(SetArea.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orgId", orgId);
            criteria.andEqualTo("isDeleted", 0);
            criteria.andEqualTo("state", 0);
            example.setOrderByClause("create_time DESC");
            return areaMapper.selectByExample(example);
        } else {

            return areaMapper.getAllAreaOrAuth(userId);
        }
    }

    /**
     * 供应商-新增
     * @param supplier
     * @return
     */
    public SetSupplier addSupplier(SetSupplier supplier){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        Example example = new Example(SetSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", supplier.getName());
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        SetSupplier setSupplier = supplierMapper.selectOneByExample(example);
        if(setSupplier != null){
            throw new LogicException("供应商已存在");
        }

        supplier.setState(0);
        supplier.setIsDeleted(0);
        supplier.setCreateUser(userId);
        supplier.setCreateTime(TimeTool.getCurrentTimeStr());
        supplier.setUpdateUser(userId);
        supplier.setUpdateTime(TimeTool.getCurrentTimeStr());
        supplier.setOrgId(orgId);
        supplierMapper.insertSelective(supplier);
        return supplier;
    }

    /**
     * 供应商-编辑
     * @param supplier
     * @return
     */
    public SetSupplier updSupplier(SetSupplier supplier){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        Example example = new Example(SetSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", supplier.getName());
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        SetSupplier setSupplier = supplierMapper.selectOneByExample(example);
        if(setSupplier != null && !setSupplier.getId().equals(supplier.getId())){
            throw new LogicException("供应商已存在");
        }

        supplier.setUpdateUser(userId);
        supplier.setUpdateTime(TimeTool.getCurrentTimeStr());
        supplierMapper.updateByPrimaryKeySelective(supplier);
        return supplier;
    }

    /**
     * 供应商-删除
     * @param id
     */
    public void delSupplier(String id){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        //该供应商下存在资产信息,不能进行删除！AssetSupplier
        Example example = new Example(AssetSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("supplierId", id);
        int count = assetSupplierMapper.selectCountByExample(example);
        if(count > 0){
            throw new LogicException("供应商在资产中已使用，不可删除");
        }

        SetSupplier supplier = new SetSupplier();
        supplier.setId(id);
        supplier.setIsDeleted(1);
        supplier.setUpdateUser(userId);
        supplier.setUpdateTime(TimeTool.getCurrentTimeStr());
        supplierMapper.updateByPrimaryKeySelective(supplier);
    }

    /**
     * 供应商-启用、禁用
     * @param supplier
     */
    public void enOrDisSupplier(SetSupplier supplier){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        supplier.setUpdateUser(userId);
        supplier.setUpdateTime(TimeTool.getCurrentTimeStr());
        supplierMapper.updateByPrimaryKeySelective(supplier);
    }

    /**
     * 供应商-分页查询
     * @param pageParams
     * @return
     */
    public List<SetSupplier> getAllPageSupplier(PageParams<SetSupplier> pageParams){
        String orgId = request.getHeader("orgId");

        PageHelper.startPage(pageParams.getCurrentPage(), pageParams.getPerPageTotal());
        Example example = new Example(SetSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        example.setOrderByClause("create_time DESC");
        return supplierMapper.selectByExample(example);
    }

    /**
     * 供应商-启用列表
     * @return
     */
    public List<SetSupplier> getAllSupplier(){
        String orgId = request.getHeader("orgId");

        Example example = new Example(SetSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        criteria.andEqualTo("state", 0);
        example.setOrderByClause("create_time DESC");
        return supplierMapper.selectByExample(example);
    }

    /**
     * 员工自助-设置
     * 0选中，1取消
     * type 1.领用、借用 2.交接
     * 如果type=1,根据所有数据receiveBorrow=1，再更新ids数据等于0
     * 如果type=2,根据所有数据handover=1，再更新ids数据等于0
     */
    public void setEmployeeSelf(SetEmployeeSelf ss){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        SetClass setclass = new SetClass();
        setclass.setUpdateUser(userId);
        setclass.setUpdateTime(TimeTool.getCurrentTimeStr());

        if(ss.getType() == 1){
            setclass.setReceiveBorrow(1);
            classMapper.updateByExampleSelective(setclass, example);

            if(ss.getIds() != null && ss.getIds().size()>0){
                criteria.andIn("id", ss.getIds());
                setclass.setReceiveBorrow(0);
                classMapper.updateByExampleSelective(setclass, example);
            }

        } else if (ss.getType() == 2){
            setclass.setHandover(1);
            classMapper.updateByExampleSelective(setclass, example);

            if(ss.getIds() != null && ss.getIds().size()>0){
                criteria.andIn("id", ss.getIds());
                setclass.setHandover(0);
                classMapper.updateByExampleSelective(setclass, example);
            }
        }

    }

    /**
     * 员工自助-删除
     * @param ss
     */
    public void delEmployeeSelf(SetEmployeeSelf ss){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        SetClass setclass = new SetClass();
        setclass.setId(ss.getId());
        setclass.setUpdateUser(userId);
        setclass.setUpdateTime(TimeTool.getCurrentTimeStr());
        if(ss.getType() == 1){
            setclass.setReceiveBorrow(1);
        } else if (ss.getType() == 2){
            setclass.setHandover(1);
        }
        classMapper.updateByPrimaryKeySelective(setclass);
    }

    /**
     * 员工自助-查询
     */
    public List<SetClass> selEmployeeSelf(){
        String orgId = request.getHeader("orgId");

        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDeleted", 0);
        criteria.andEqualTo("state", 0);
        criteria.andEqualTo("receiveBorrow", 0);
        return classMapper.selectByExample(example);
    }

    /**
     * 根据类型id获取授权管理员id
     * @param idList
     * @return
     */
    public String[] getUserIdByModelId(List<String> idList){
        return classMapper.getUserIdByModelId(idList);
    }

    /**
     * 通过类别编号查询资产类别
     * @param classNum
     * @return
     */
    public SetClass queryAssetClassByNum(String classNum){
        // 通过类别编号查询资产类别
        String token = request.getHeader("token");
        String orgId = cacheUtils.getUserCompanyId(token);
        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("num",classNum);
        criteria.andEqualTo("orgId",orgId);
        SetClass setClass = classMapper.selectOneByExample(example);
        return setClass;
    }

    public StandModel queryStandModelByName(String model){
        // 通过类别编号查询资产类别
        String token = request.getHeader("token");
        String orgId = cacheUtils.getUserCompanyId(token);
        Example example = new Example(StandModel.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("model",model);
        StandModel standModel = standModelMapper.selectOneByExample(example);
        return standModel;
    }
    public SetArea queryAreaByAreaNum(String num){
        // 通过类别编号查询资产类别
        String token = request.getHeader("token");
        String orgId = cacheUtils.getUserCompanyId(token);
        Example example = new Example(SetArea.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type",num);
        criteria.andEqualTo("orgId",orgId);
        criteria.andEqualTo("isDeleted",0);
        SetArea setArea = areaMapper.selectOneByExample(example);
        return setArea;
    }

    public SetSupplier querySupplierByName(String supplierName){
        // 通过类别编号查询资产类别
        String token = request.getHeader("token");
        String orgId = cacheUtils.getUserCompanyId(token);
        Example example = new Example(SetSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name",supplierName);
        criteria.andEqualTo("orgId",orgId);
        criteria.andEqualTo("isDeleted",0);
        SetSupplier setSupplier = supplierMapper.selectOneByExample(example);
        return setSupplier;
    }
}
